package com.kusen.text;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.kusen.text.SignatureDemo.caculateSignature;
import static com.kusen.text.StringTest.getRandomString;

public class FuFeiTest {
    public static void main(String[] args) {
        FuFeiTest fuFeiTest = new FuFeiTest();
        try {
            String url = fuFeiTest.url("40412609,40194923");
            String s = SignatureDemo.doGet(url);
            System.out.println(s);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    //https://api.ximalaya.com/open_pay/batch_get_paid_albums?
    // app_key=b617866c20482d133d5de66fceb37da3
    // &client_os_type=4
    // &nonce=ae8ed1714fdd0507480c4714a46cd25f
    // &server_api_version=1.0.0
    // &ids=4615999
    // &sig=de319e614607d04dcb7b241e4ed2e693

    public String url(String ids) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        Map<String, String> link = new LinkedHashMap<>();
        link.put("app_key", XimalayaConfig.app_key);
        link.put("client_os_type", "4");
        String nonce = getRandomString(32);
        link.put("nonce", nonce);
        String timestamp = String.valueOf(new Date().getTime());
        link.put("timestamp", timestamp);
        link.put("server_api_version", "1.0.0");
        link.put("ids", ids);
        String keep = XimalayaConfig.app_secret + XimalayaConfig.serverAuthenticateStaticKey;
        String sig = caculateSignature(link, keep);
        link.put("sig", sig);
        StringBuffer sb = new StringBuffer(XimalayaConfig.url).append(XimalayaConfig.album_tracks_rul).append("?");
        //发送http请求
        //System.out.println(getCompleteUrl(sb, link));
        //String data = SignatureDemo.doGet(getCompleteUrl(sb, link));
        return getCompleteUrl(sb, link);
    }

    private String getCompleteUrl(StringBuffer sb, Map<String, String> result) {
        for (Map.Entry<String, String> entry : result.entrySet()) {
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            sb.append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
